package be.ipl.finito.servlets;

import java.io.IOException;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import be.ipl.finito.domaine.Joueur;
import be.ipl.finito.domaine.Partie;
import be.ipl.finito.exceptions.BizException;
import be.ipl.finito.usecases.GestionParties;

@SuppressWarnings("serial")
@WebServlet(name = "attente.html")
public class Attente extends HttpServlet implements Servlet {

	@EJB
	GestionParties gp;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		int id = Integer.parseInt(req.getParameter("id"));
		HttpSession session = req.getSession();
		Joueur moi = (Joueur) session.getAttribute("joueur");
		Partie recherchee = gp.getPartieById(id);
		if (recherchee == null) {
			req.setAttribute("messageErreur", "Partie introuvable");
			RequestDispatcher rd = getServletContext().getNamedDispatcher(
					"listerparties.html");

			rd.forward(req, resp);
			return;
		}

		RequestDispatcher rd = getServletContext()
				.getNamedDispatcher("Attente");
		List<Joueur> autres = null;
		try {
			autres = gp.getJoueurs(recherchee);
		} catch (BizException e) {
			req.setAttribute("messageErreur", "Partie introuvable");
			rd = getServletContext().getNamedDispatcher(
					"listerparties.html");
			rd.forward(req, resp);
			
		}
		autres.remove(moi);
		req.setAttribute("partie", recherchee);
		session.setAttribute("joueurs", autres);
		rd.forward(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
}